<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/02/17
 * Time: 16:15
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\wms;

use app\admin\controller\BaseController;
use app\common\library\Tools;
use app\common\model\ChannelExpress;
use app\common\model\Warehouse;
use app\common\model\WarehouseAllot;
use app\common\model\WarehouseStock;
use app\common\service\product\WarehouseService;

/**
 * 仓库调拨
 * Class WallotController
 * @package app\admin\controller\wms
 */
class WallotController extends BaseController
{
    protected $moduleName = 'warehouse_allot';

    /**
     * 调拨单列表
     * @date 2021/02/17
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $allot = WarehouseAllot::with(['win', 'wout', 'user'])
                ->where('out_id', $this->warehouse->warehouse_id)
                ->order('allot_id desc');
            $this->searchModel($allot, [
                'eq' => ['allot_sn', 'in_id', 'user_id', 'check_status', 'status', 'allot_num'],
                'times' => ['allot_date', 'out_date', 'finish_date']
            ]);
            $limit = $this->getPageSize();
            $allot = $allot->paginate($limit);
            $this->assign('track_status_none', ChannelExpress::TRACK_STATUS_NONE);
            $this->assign('status_wait', WarehouseAllot::ALLOT_STATUS_WAIT);
            $this->assign('status_cancel', WarehouseAllot::ALLOT_STATUS_CANCEL);
            $this->assign('is_show_check', $this->user->hasPermissions('/wms/wallot/check'));
            $this->assign("list", $allot->getCollection());
            $this->assign("page", $allot->render());
            return $this->fetch('lists');
        }
        $this->assign('warehouse', Warehouse::getAll());
        $this->assign('users', \app\common\model\Admin::getAll());
        $this->assign('check_status', \app\common\model\JobFlowModule::$CHECK_STATUS);
        $this->assign('status', WarehouseAllot::$ALLOT_STATUS);
        return $this->fetch('index');
    }

    /**
     * 调拨单详情
     * @date 2021/02/17
     * @author longli
     */
    public function info()
    {
        $allotId = $this->request->get('allot_id');
        if(empty($allotId)) $this->error('非法请求');
        if(!($allot = WarehouseAllot::get($allotId))) $this->error('调拨单不存在');
        $this->assign('allot', $allot);
        $this->assignCheck($allotId);
        $this->assign('allot_info', $this->renderTerp(WarehouseAllot::class, $allot->allot_id, "wms/warehouse/terp/check_info"));
        return $this->fetch('info');
    }

    /**
     * 调拨单追踪号详情
     * @date 2020/12/22
     * @author longli
     */
    public function tinfo()
    {
        $allotId = $this->request->get("allot_id");
        if(empty($allotId)) $this->error("非法请求");
        $allot = WarehouseAllot::get($allotId);
        if(empty($allot)) $this->error("调拨单不存在");
        if(empty($allot->track_info)) $this->error("暂无物流信息");
        $trackInfo = json_decode($allot->track_info, true);
        $this->assign("trackInfo", $trackInfo);
        return $this->fetch("pur/track/track_info");
    }

    /**
     * 添加调拨单
     * @date 2021/02/17
     * @author longli
     */
    public function add()
    {
        $allotId = $this->request->get('allot_id');
        $this->assign('express', ChannelExpress::getAll());
        if(!empty($allotId))
        {
            $this->assign('allot', WarehouseAllot::get($allotId));
            return $this->fetch('edit');
        }
        $this->assign('warehouse', Warehouse::getAll());
        return $this->fetch('add');
    }

    /**
     * 保存调拨单
     * @date 2021/02/17
     * @author longli
     */
    public function save()
    {
        $info = [];
        if($this->request->isPost())
        {
            if($this->request->post('allot_id', '') != '')
            {
                $data = $this->request->post();
            }
            else
            {
                $this->validateSave();
                $data = [
                    'user_id' => $this->user->id,
                    'out_id' => $this->warehouse->warehouse_id, // 调出仓库
                    ] + json_decode($this->request->getContent(), true);
                foreach($data['sku'] as $k => $sku)
                {
                    $info[] = [
                        'sku' => $sku,
                        'qty' => $data['qty'][$k],
                        'remark' => isset($data['t_remark']) ? $data['t_remark'][$k] : '',
                    ];
                }
            }
        }
        else
        {
            $this->validateSave();
            $data = $this->request->only(['allot_id', 'status'], 'get');
        }
        if(!empty($data['express_id'])) $data['logistics_name'] = ChannelExpress::getNameById($data['express_id']);
        WarehouseService::getInstance()->addAllot($data, $info)
            ? $this->success('操作成功')
            : $this->error('操作失败');
    }

    /**
     * 验证调拨单
     * @date 2021/02/18
     * @author longli
     */
    private function validateSave()
    {
        if($this->request->isPost())
        {
            if(!Tools::isJson($this->request->getContent(), $data))
                $this->error('数据格式有误');
            $validate = \think\facade\Validate::make([
                'in_id'  => 'require',
                'allot_date'  => 'require|date',
                'sku' => 'require|array',
                'qty' => 'require|array',
            ],[
                'in_id.require' => '调入仓库必选',
                'allot_date.require' => '调拨日期必填',
                'allot_date.date' => '调拨日期有误',
                'sku.require' => 'SKU 必选',
                'sku.array' => 'SKU 必须是数组',
                'qty.require' => '数量必填',
                'qty.array' => '数量必须是数组',
            ]);
            if(!$validate->batch()->check($data)) $this->error(join(', ', $validate->getError()));
            if($this->warehouse->warehouse_id == $data['in_id']) $this->error('调出仓库和调入仓库不能相同');
            foreach($data['sku'] as $k => $sku)
            {
                $qty = intval($data['qty'][$k]);
                if($qty < 1) $this->error("调拨SKU【{$sku}】数量不能小于1");
                if(!WarehouseStock::isEnough($this->warehouse->warehouse_id, $sku, $qty)) $this->error("SKU【{$sku}】库存不足");
            }
        }
        else
        {
            $data = $this->request->only(['allot_id', 'status'], 'get');
            if(!isset($data['allot_id']) || !($allot = WarehouseAllot::get($data['allot_id'])))
                $this->error('非法请求');
            if(isset($data['status']) && $data['status'] == WarehouseAllot::ALLOT_STATUS_CANCEL
                && in_array($allot->getData('status'), [WarehouseAllot::ALLOT_STATUS_ING, WarehouseAllot::ALLOT_STATUS_SUCC]))
            {
                $this->error('已调拨的订单不能取消');
            }
        }
    }
}